<template>
    <el-row :gutter="20">
        <el-col :sm="24" :lg="8">
            <el-card>
                <template #header>
                    <div class="card-header">
                        <h5>🧱 系统（硬件）信息</h5>
                        <div class="card-refresh-btn"><el-button circle @click="initSystemInfo(true)"><el-icon><Refresh /></el-icon></el-button></div>
                    </div>
                </template>
                <el-empty :image-size="200" v-if="!windowStore.systemInfo" />
                <el-descriptions v-else class="margin-top" :column="1" border style="height: 320px;">
                    <el-descriptions-item><template #label>
                            <div class="cell-item">生产商:</div>
                        </template>{{ windowStore.systemInfo.生产商 }}</el-descriptions-item>
                    <el-descriptions-item><template #label>
                            <div class="cell-item">型号:</div>
                        </template>{{ windowStore.systemInfo.型号 }}</el-descriptions-item>
                    <el-descriptions-item><template #label>
                            <div class="cell-item">BIOS厂商:</div>
                        </template>{{ windowStore.systemInfo.BIOS厂商 }}</el-descriptions-item>
                    <el-descriptions-item><template #label>
                            <div class="cell-item">BIOS版本:</div>
                        </template>{{ windowStore.systemInfo.BIOS版本 }}</el-descriptions-item>
                    <el-descriptions-item><template #label>
                            <div class="cell-item">BIOS发布日期:</div>
                        </template>{{ windowStore.systemInfo.BIOS发布日期 }}</el-descriptions-item>
                    <el-descriptions-item><template #label>
                            <div class="cell-item">主板厂商:</div>
                        </template>{{ windowStore.systemInfo.主板厂商 }}</el-descriptions-item>
                    <el-descriptions-item><template #label>
                            <div class="cell-item">主板型号:</div>
                        </template>{{ windowStore.systemInfo.主板型号 }}</el-descriptions-item>
                    <el-descriptions-item><template #label>
                            <div class="cell-item">主板版本:</div>
                        </template>{{ windowStore.systemInfo.主板版本 }}</el-descriptions-item>
                </el-descriptions>
            </el-card>
        </el-col>
        <el-col :sm="24" :lg="8">
            <el-card>
                <template #header>
                    <div class="card-header">
                        <h5>🧠 CPU 信息</h5>
                        <div class="card-refresh-btn"><el-button circle @click="initCpuInfo(true)"><el-icon><Refresh /></el-icon></el-button></div>
                    </div>
                </template>
                <el-empty :image-size="200" v-if="!windowStore.cpuInfo" />
                <el-descriptions v-else class="margin-top" :column="1" border style="height: 320px;">
                    <el-descriptions-item><template #label>
                            <div class="cell-item">厂商:</div>
                        </template>{{ windowStore.cpuInfo.厂商 }}</el-descriptions-item>
                    <el-descriptions-item><template #label>
                            <div class="cell-item">品牌:</div>
                        </template>{{ windowStore.cpuInfo.品牌 }}</el-descriptions-item>
                    <el-descriptions-item><template #label>
                            <div class="cell-item">频率:</div>
                        </template>{{ windowStore.cpuInfo.频率 }}</el-descriptions-item>
                    <el-descriptions-item><template #label>
                            <div class="cell-item">核心数:</div>
                        </template>{{ windowStore.cpuInfo.核心 }}</el-descriptions-item>
                    <el-descriptions-item><template #label>
                            <div class="cell-item">物理核心:</div>
                        </template>{{ windowStore.cpuInfo.物理核心 }}</el-descriptions-item>
                    <el-descriptions-item><template #label>
                            <div class="cell-item">处理器数量:</div>
                        </template>{{ windowStore.cpuInfo.处理器 }}</el-descriptions-item>
                    <el-descriptions-item><template #label>
                            <div class="cell-item">CPU平均频率:</div>
                        </template>{{ windowStore.cpuInfo.CPU平均频率 }}GHz</el-descriptions-item>
                </el-descriptions>
            </el-card>
        </el-col>
        <el-col :sm="24" :lg="8">
            <el-card>
                <template #header>
                    <div class="card-header">
                        <h5>💻 系统信息</h5>
                        <div class="card-refresh-btn"><el-button circle @click="initOsInfo(true)"><el-icon><Refresh /></el-icon></el-button></div>
                    </div>
                </template>
                <el-empty :image-size="200" v-if="!windowStore.osInfo" />
                <el-descriptions v-else class="margin-top"  :column="1" border style="height: 320px;">
                    <el-descriptions-item><template #label>
                            <div class="cell-item">平台:</div>
                        </template>{{ windowStore.osInfo?.平台 }}</el-descriptions-item>
                    <el-descriptions-item><template #label>
                            <div class="cell-item">系统:</div>
                        </template>{{ windowStore.osInfo?.系统 }}</el-descriptions-item>
                    <el-descriptions-item><template #label>
                            <div class="cell-item">发行版:</div>
                        </template>{{ windowStore.osInfo?.发行版 }}</el-descriptions-item>
                    <el-descriptions-item><template #label>
                            <div class="cell-item">版本号:</div>
                        </template>{{ windowStore.osInfo?.版本号 }}</el-descriptions-item>
                    <el-descriptions-item><template #label>
                            <div class="cell-item">内核:</div>
                        </template>{{ windowStore.osInfo?.内核 }}</el-descriptions-item>
                    <el-descriptions-item><template #label>
                            <div class="cell-item">主机名:</div>
                        </template>{{ windowStore.osInfo?.主机名 }}</el-descriptions-item>
                    <el-descriptions-item><template #label>
                            <div class="cell-item">用户目录:</div>
                        </template>{{ windowStore.osInfo?.用户目录 }}</el-descriptions-item>
                </el-descriptions>
            </el-card>
        </el-col>
        <!-- 内存 -->
        <el-col :sm="24" :lg="8">
            <el-card shadow="hover">
                <template #header>
                    <div class="card-header">
                        <h5>⚙️ 内存</h5>
                        <div class="card-refresh-btn"><el-button circle @click="initMemoryChart(true)"><el-icon><Refresh /></el-icon></el-button></div>
                    </div>
                </template>
                <div ref="memoryChartRef" style="height: 320px; width: 100%;"></div>
            </el-card>
        </el-col>
        <!-- 磁盘 -->
        <el-col :sm="24" :lg="8">
            <el-card shadow="hover">
                <template #header>
                    <div class="card-header">
                        <h5>⚙️ 磁盘</h5>
                        <div class="card-refresh-btn"><el-button circle @click="initDiskChart(true)"><el-icon><Refresh /></el-icon></el-button></div>
                    </div>
                </template>
                <div ref="diskChartRef" style="height: 320px; width: 100%;"></div>
            </el-card>
        </el-col>
        <!-- 实时CPU走势 -->
        <el-col :sm="24" :lg="8">
            <el-card shadow="always">
                <template #header>
                    <div class="card-header">
                        <h5>⚙️ CPU 负载实时走势</h5>
                        <div class="card-refresh-btn"><el-button circle @click="handleResize()"><el-icon><Refresh /></el-icon></el-button></div>
                    </div>
                </template>
                <div ref="cpuTrendChartRef" style="height: 320px; width: 100%;"></div>
            </el-card>
        </el-col>
        <el-col :xl="24">
            <el-collapse v-model="activeNames" accordion>
                <el-collapse-item title="&nbsp;&nbsp;分区信息" name="1">
                    <el-empty :image-size="200" v-if="!windowStore.fsInfo" />
                    <div v-for="(item, index) in windowStore.fsInfo" :key="index" style="padding: 0;margin: 10px;"
                        v-else>
                        <el-card shadow="hover">
                            <el-descriptions direction="vertical" :column="5" border class="margin-top">
                                <el-descriptions-item label="挂载点" width="20%">{{ item.挂载点 }}</el-descriptions-item>
                                <el-descriptions-item label="文件系统类型" width="20%">{{ item.文件系统类型
                                    }}</el-descriptions-item>
                                <el-descriptions-item label="容量" width="20%">{{ formatBytes(item.容量)
                                    }}</el-descriptions-item>
                                <el-descriptions-item label="已使用容量" width="20%">{{ formatBytes(item.已使用容量)
                                    }}</el-descriptions-item>
                                <el-descriptions-item label="使用率" width="20%">{{ item.使用率 }}</el-descriptions-item>
                            </el-descriptions>
                        </el-card>
                    </div>
                </el-collapse-item>
                <el-collapse-item title="&nbsp;&nbsp;磁盘信息" name="2">
                    <el-empty :image-size="200" v-if="!windowStore.diskInfo" />
                    <el-col v-for="(item, index) in windowStore.diskInfo" :key="index" style="padding: 0;margin: 10px;"
                        v-else>
                        <el-card shadow="hover">
                            <el-descriptions direction="vertical" :column="5" border class="margin-top">
                                <el-descriptions-item label="名称">{{ item.名称 }}</el-descriptions-item>
                                <el-descriptions-item label="类型" width="15%">{{ item.类型 }}</el-descriptions-item>
                                <el-descriptions-item label="容量 (字节)" width="15%">{{ formatBytes(item.容量)
                                    }}</el-descriptions-item>
                                <el-descriptions-item label="接口类型" width="15%">{{ item.接口类型 }}</el-descriptions-item>
                                <el-descriptions-item label="smart状态" width="15%">{{ item.smart状态
                                    }}</el-descriptions-item>
                            </el-descriptions>
                        </el-card>
                    </el-col>
                </el-collapse-item>
                <el-collapse-item title="&nbsp;&nbsp;显卡信息" name="3">
                    <el-empty :image-size="200" v-if="!windowStore.graphInfo" />
                    <el-col v-for="(item, index) in windowStore.graphInfo" :key="index" style="padding: 0;margin: 10px;"
                        v-else>
                        <el-card shadow="hover">
                            <el-descriptions direction="vertical" :column="4" border class="margin-top">
                                <el-descriptions-item label="型号" width="15%">{{ item.型号 }}</el-descriptions-item>
                                <el-descriptions-item label="生产商">{{ item.生产商 }}</el-descriptions-item>
                                <el-descriptions-item label="显存" width="15%">{{ item.显存 }}</el-descriptions-item>
                                <el-descriptions-item label="是否动态显存" width="15%">{{ item.是否动态显存
                                    }}</el-descriptions-item>
                            </el-descriptions>
                        </el-card>
                    </el-col>
                </el-collapse-item>
                <el-collapse-item title="&nbsp;&nbsp;网络信息" name="4">
                    <el-empty :image-size="200" v-if="!windowStore.networkInfo" />
                    <el-col v-for="(item, index) in windowStore.networkInfo.网卡" :key="index"
                        style="padding: 0;margin: 10px;" v-else>
                        <el-card shadow="hover">
                            <el-descriptions direction="vertical" :column="5" border class="margin-top">
                                <el-descriptions-item label="网络连接" width="35%">{{ item.网络连接 }}</el-descriptions-item>
                                <el-descriptions-item label="网卡名称" width="35%">{{ item.网卡名称 }}</el-descriptions-item>
                                <el-descriptions-item label="IP地址" width="10%">{{ item.IP地址 }}</el-descriptions-item>
                                <el-descriptions-item label="mac地址" width="10%">{{ item.mac地址 }}</el-descriptions-item>
                                <el-descriptions-item label="连接类型" width="10%">{{ item.连接类型 }}</el-descriptions-item>
                            </el-descriptions>
                        </el-card>
                    </el-col>
                </el-collapse-item>
                <el-collapse-item title="&nbsp;&nbsp;CPU核心负载" name="5">
                    <el-empty :image-size="200" v-if="!cpuCoreData" />
                    <el-col v-for="(item, index) in cpuCoreData" :key="index" style="padding: 0;margin: 10px;" v-else>
                        <el-card shadow="hover">
                            <el-descriptions direction="vertical" :column="5" border class="margin-top">
                                <el-descriptions-item label="核心编号" width="20%">{{ item.核心编号 }}</el-descriptions-item>
                                <el-descriptions-item label="用户负载" width="20%">{{ item.用户负载 }}</el-descriptions-item>
                                <el-descriptions-item label="系统负载" width="20%">{{ item.系统负载 }}</el-descriptions-item>
                                <el-descriptions-item label="当前负载" width="20%">{{ item.当前负载 }}</el-descriptions-item>
                                <el-descriptions-item label="平均负载" width="20%">{{ item.平均负载 }}</el-descriptions-item>
                            </el-descriptions>
                        </el-card>
                    </el-col>
                </el-collapse-item>
                <el-collapse-item title="&nbsp;&nbsp;进程" name="6">
                    <el-card shadow="always" style="padding: 0;margin: 10px;">
                        <el-button circle @click="expandedALL">{{ expandedRowKeys.length == 0 ? '展开' : '折叠'
                            }}</el-button>
                        <!-- <json-viewer :value="proceData" /> -->
                        <el-table-v2 :columns="columns" :data="treeData" row-key="pid"
                            :width="windowStore.winWidth - 95" :height="360" :expand-column-key="columns[0].key"
                            v-model:expanded-row-keys="expandedRowKeys">
                            <template #empty>
                                <div class="flex items-center justify-center h-100%">
                                    <el-empty />
                                </div>
                            </template>
                        </el-table-v2>
                    </el-card>
                </el-collapse-item>
            </el-collapse>
        </el-col>
    </el-row>
</template>
<script>
    import { h, watch, getCurrentInstance } from 'vue';
    import { Refresh } from '@element-plus/icons-vue'
    import { storeToRefs } from 'pinia';
    import { useWindowStore } from '/src/stores/windowStore';
    import { ElMessage, ElLoading, ElTableV2 } from 'element-plus'
    import { ipcRenderer } from 'electron';
    //import JsonViewer from 'vue3-json-viewer'
    import * as echarts from 'echarts';
    export default {
        data() {
            return {
                activeNames: ['1'],//默认展开项
                maxPoints: 30,//走势显示条数
                cpuTrendChart: null,//CPU 负载实时走势
                cpuCoreData: [],// 构造 CPU 核心表格数据
                memoryChart: null,//内存
                diskChart: null,//磁盘
                memoryChartRef: null,
                diskChartRef: null,
                cpuTrendChartRef: null,
                proceData: null,
                pidMap: {},
                treeData: [],
                expandedRowKeys: [],
            };
        },
        setup() {
            const windowStore = useWindowStore();
            const instance = getCurrentInstance();
            watch(() => windowStore.winWidth,
                (newVal, oldVal) => {
                    if (newVal !== oldVal && instance.proxy) {
                        instance.proxy.handleResize(); // ✅ 使用 proxy 调用方法
                    }
                }
            );
            return { windowStore };
        },
        mounted() {
            this.$nextTick(() => {
                setTimeout(async () => {
                    try {
                        //系统（硬件）信息
                        await this.initSystemInfo(false);
                        //CPU信息
                        await this.initCpuInfo(false);
                        //显卡信息
                        await this.initGraphInfo(false);
                        //系统信息
                        await this.initOsInfo(false);
                        //磁盘信息
                        await this.initDiskInfo(false);
                        //网络信息
                        await this.initNetworkInfo(false);
                        //内存信息
                        await this.initMemoryChart(false);
                        //分区信息
                        await this.initDiskChart(false);
                        //进程和性能信息
                        await this.initCpuTrendChart();

                        await this.startAutoUpdate();

                        const result = await ipcRenderer.invoke('system-info', 'proce');
                        if (result.code == 200) {
                            let otherExe = ['wininit.exe', 'explorer.exe'];
                            let data = result.data.list.filter(function (item) { return item.pid > 0 && otherExe.indexOf(item.name) == -1 });//.map(function(item){return {name: item.name, pid: item.pid, parentPid: item.parentPid, command: item.command}});
                            data.forEach(proc => {
                                const parent_node = data.filter(function (item) { return item.pid == proc.parentPid });
                                if (parent_node.length == 0) {
                                    proc.parentPid = 0;
                                }
                            })
                            this.treeData = await this.buildProcessTree(data);
                        }
                    } catch (error) {
                        console.log(error);
                    }
                }, 100); // 延迟 100ms
            });
        },
        components: {
            ElTableV2,
        },
        computed: {
            columns() {
                return [
                    {
                        key: 'name', title: '进程名', dataKey: 'name', width: 600,
                        cellRenderer: ({ rowData, rowIndex }) => {
                            //const level = this.getLevel(rowData);
                            //style: { paddingLeft: `${level * 10 + (rowData.children.length === 0 ? 4 : 0)}px` }
                            return h('div', {}, rowData.name);
                        }
                    },
                    { key: 'pid', title: '进程ID', dataKey: 'pid', width: 100 },
                    { key: 'parentPid', title: '父进程ID', dataKey: 'parentPid', width: 100 },
                    { key: 'command', title: '启动命令', dataKey: 'command', width: 100 },
                    { key: 'path', title: '可执行文件路径', dataKey: 'path', width: 100 },
                    { key: 'started', title: '进程启动时间', dataKey: 'started', width: 180 },
                    //{ key: 'state', title: '进程状态', dataKey: 'state', width: 100 },
                    { key: 'priority', title: '进程优先级', dataKey: 'priority', width: 100 },
                    // { key: 'user', title: '启动该进程的用户名称', dataKey: 'user', width: 100 },
                    // { key: 'tty', title: '关联的终端设备', dataKey: 'tty', width: 100 },
                    // { key: 'params', title: '启动参数', dataKey: 'params', width: 100 },
                    //{ key: 'nice', title: '调度优先级调整值', dataKey: 'nice', width: 100 },
                    {
                        key: 'cpu', title: 'CPU 使用率（百分比）', dataKey: 'cpu', width: 100, cellRenderer: ({ cellData: cpu }) => (
                            cpu.toFixed(2) + '%'
                        )
                    },
                    {
                        key: 'cpus', title: '内核态 CPU 使用率', dataKey: 'cpus', width: 100, cellRenderer: ({ cellData: cpus }) => (
                            cpus.toFixed(2) + '%'
                        )
                    },
                    {
                        key: 'cpuu', title: '用户态 CPU 使用率', dataKey: 'cpuu', width: 100, cellRenderer: ({ cellData: cpuu }) => (
                            cpuu.toFixed(2) + '%'
                        )
                    },
                    {
                        key: 'mem', title: '内存使用率（百分比）', dataKey: 'mem', width: 100, cellRenderer: ({ cellData: mem }) => (
                            mem.toFixed(2) + '%'
                        )
                    },
                    { key: 'memRss', title: '常驻内存大小（字节）', dataKey: 'memRss', width: 100 },
                    { key: 'memVsz', title: '虚拟内存大小（字节）', dataKey: 'memVsz', width: 100 }
                ];
            }
        },
        methods: {
            //系统（硬件）信息
            async initSystemInfo(state) {
                try {
                    if (this.windowStore.systemInfo === null || state) {
                        const loading = ElLoading.service({
                            lock: true,
                            text: 'Loading',
                            background: 'rgba(0, 0, 0, 0.7)',
                        });
                        const result = await ipcRenderer.invoke('system-info', 'system');
                        //console.log('systemInfo:', result);
                        if (result.code == 200) {
                            this.windowStore.updateSystem('system', result.data);
                        } else {
                            ElMessage({
                                message: result.msg,
                                type: 'error',
                                plain: true,
                            })
                        }
                        setTimeout(() => {
                            loading.close()
                        }, 100)
                    }
                } catch (error) {
                    console.log(error);
                }
            },
            //CPU信息
            async initCpuInfo(state) {
                try {
                    if (this.windowStore.cpuInfo === null || state) {
                        const loading = ElLoading.service({
                            lock: true,
                            text: 'Loading',
                            background: 'rgba(0, 0, 0, 0.7)',
                        });
                        const result = await ipcRenderer.invoke('system-info', 'cpu');
                        //console.log('cpuInfo:', result);
                        if (result.code == 200) {
                            this.windowStore.updateSystem('cpu', result.data);
                        } else {
                            ElMessage({
                                message: result.msg,
                                type: 'error',
                                plain: true,
                            })
                        }
                        setTimeout(() => {
                            loading.close()
                        }, 100)
                    }
                } catch (error) {
                    console.log(error);
                }
            },
            //系统信息
            async initOsInfo(state) {
                try {
                    if (this.windowStore.osInfo === null || state) {
                        const loading = ElLoading.service({
                            lock: true,
                            text: 'Loading',
                            background: 'rgba(0, 0, 0, 0.7)',
                        });
                        const result = await ipcRenderer.invoke('system-info', 'os');
                        //console.log('osInfo:', result);
                        if (result.code == 200) {
                            this.windowStore.updateSystem('os', result.data);
                        } else {
                            ElMessage({
                                message: result.msg,
                                type: 'error',
                                plain: true,
                            })
                        }
                        setTimeout(() => {
                            loading.close()
                        }, 100)
                    }
                } catch (error) {
                    console.log(error);
                }
            },
            //显卡信息
            async initGraphInfo(state) {
                try {
                    if (this.windowStore.graphInfo === null || state) {
                        const loading = ElLoading.service({
                            lock: true,
                            text: 'Loading',
                            background: 'rgba(0, 0, 0, 0.7)',
                        });
                        const result = await ipcRenderer.invoke('system-info', 'graph');
                        //console.log('graphInfo:', result);
                        if (result.code == 200) {
                            this.windowStore.updateSystem('graph', result.data);
                        } else {
                            ElMessage({
                                message: result.msg,
                                type: 'error',
                                plain: true,
                            })
                        }
                        setTimeout(() => {
                            loading.close()
                        }, 100)
                    }
                } catch (error) {
                    console.log(error);
                }
            },
            //磁盘信息
            async initDiskInfo(state) {
                try {
                    if (this.windowStore.diskInfo === null || state) {
                        const loading = ElLoading.service({
                            lock: true,
                            text: 'Loading',
                            background: 'rgba(0, 0, 0, 0.7)',
                        });
                        const result = await ipcRenderer.invoke('system-info', 'disk');
                        //console.log('diskInfo:', result);
                        if (result.code == 200) {
                            this.windowStore.updateSystem('disk', result.data);
                        } else {
                            ElMessage({
                                message: result.msg,
                                type: 'error',
                                plain: true,
                            })
                        }
                        setTimeout(() => {
                            loading.close()
                        }, 100)
                    }
                } catch (error) {
                    console.log(error);
                }
            },
            //网络信息
            async initNetworkInfo(state) {
                try {
                    if (this.windowStore.networkInfo === null || state) {
                        const loading = ElLoading.service({
                            lock: true,
                            text: 'Loading',
                            background: 'rgba(0, 0, 0, 0.7)',
                        });
                        const result = await ipcRenderer.invoke('system-info', 'network');
                        //console.log('networkInfo:', result);
                        if (result.code == 200) {
                            this.windowStore.updateSystem('network', result.data);
                        } else {
                            ElMessage({
                                message: result.msg,
                                type: 'error',
                                plain: true,
                            })
                        }
                        setTimeout(() => {
                            loading.close()
                        }, 100)
                    }
                } catch (error) {
                    console.log(error);
                }
            },
            //内存信息
            async initMemoryChart(state) {
                try {
                    if (this.windowStore.memInfo === null || state) {
                        const loading = ElLoading.service({
                            lock: true,
                            text: 'Loading',
                            background: 'rgba(0, 0, 0, 0.7)',
                        });
                        const result = await ipcRenderer.invoke('system-info', 'mem');
                        //console.log('memInfo:', result);
                        if (result.code == 200) {
                            this.windowStore.updateSystem('mem', result.data);
                        } else {
                            ElMessage({
                                message: result.msg,
                                type: 'error',
                                plain: true,
                            })
                        }
                        setTimeout(() => {
                            loading.close()
                        }, 100)
                    }
                    const used = this.windowStore.memInfo ? parseInt((this.windowStore.memInfo.已用内存 / this.windowStore.memInfo.总内存) * 100) : 0;
                    if (!this.memoryChart && this.$refs.memoryChartRef) {
                        this.memoryChart = echarts.init(this.$refs.memoryChartRef);
                    } else {
                        this.handleResize();
                    }
                    let _this = this;
                    this.memoryChart.setOption({
                        tooltip: {
                            trigger: 'item',
                            formatter: function (params) {
                                return params.name + ': ' + _this.formatBytes(params.value[1]) + ', ' + params.value[0] + '%';
                            }
                        },
                        series: [{
                            type: 'pie',
                            radius: '55%',
                            avoidLabelOverlap: false,
                            label: { show: true, position: 'outside', formatter: '{b}: {d}%' },
                            data: [
                                { value: [used, this.windowStore.memInfo.已用内存], name: '已使用', itemStyle: { color: '#e74c3c' } },
                                { value: [100 - used, this.windowStore.memInfo.总内存 - this.windowStore.memInfo.已用内存], name: '空闲', itemStyle: { color: '#2ecc71' } }
                            ],
                            emphasis: {
                                itemStyle: { shadowBlur: 10, shadowOffsetX: 0, shadowColor: 'rgba(0,0,0,0.5)' }
                            }
                        }]
                    });
                } catch (error) {
                    console.log(error);
                }
            },
            //磁盘信息
            async initDiskChart(state) {
                try {
                    if (this.windowStore.fsInfo === null || state) {
                        const loading = ElLoading.service({
                            lock: true,
                            text: 'Loading',
                            background: 'rgba(0, 0, 0, 0.7)',
                        });
                        const result = await ipcRenderer.invoke('system-info', 'fs');
                        //console.log('fsInfo:', result);
                        if (result.code == 200) {
                            this.windowStore.updateSystem('fs', result.data);
                        } else {
                            ElMessage({
                                message: result.msg,
                                type: 'error',
                                plain: true,
                            })
                        }
                        setTimeout(() => {
                            loading.close()
                        }, 100)
                    }
                    const usedPercent = parseFloat(this.windowStore.fsInfo ? this.windowStore.fsInfo[0].使用率 : 0);
                    if (!this.diskChart && this.$refs.diskChartRef) {
                        this.diskChart = echarts.init(this.$refs.diskChartRef);
                    } else {
                        this.handleResize();
                    }
                    let _this = this;
                    this.diskChart.setOption({
                        tooltip: {
                            trigger: 'item',
                            formatter: function (params) {
                                return params.name + ': ' + _this.formatBytes(params.value[1]) + ', ' + params.value[0] + '%';
                            }
                        },
                        series: [{
                            type: 'pie',
                            radius: '55%',
                            label: { show: true, position: 'outside', formatter: '{b}: {d}%' },
                            data: [
                                { value: [usedPercent, this.windowStore.fsInfo[0].已使用容量], name: '已使用', itemStyle: { color: '#3498db' } },
                                { value: [100 - usedPercent, this.windowStore.fsInfo[0].容量 - this.windowStore.fsInfo[0].已使用容量], name: '空闲', itemStyle: { color: '#95a5a6' } }
                            ]
                        }]
                    });
                } catch (error) {
                    console.log(error);
                }
            },
            //进程和性能信息
            async initCpuTrendChart() {
                try {
                    if (this.windowStore.loadInfo === null) {
                        const loading = ElLoading.service({
                            lock: true,
                            text: 'Loading',
                            background: 'rgba(0, 0, 0, 0.7)',
                        });
                        const result = await ipcRenderer.invoke('system-info', 'load');
                        //console.log('loadInfo:', result);
                        if (result.code == 200) {
                            this.windowStore.updateSystem('load', result.data);
                        } else {
                            ElMessage({
                                message: result.msg,
                                type: 'error',
                                plain: true,
                            })
                        }
                        setTimeout(() => {
                            loading.close()
                        }, 100)
                    }
                    // 构造 CPU 核心表格数据
                    this.cpuCoreData = this.windowStore.loadInfo ? this.windowStore.loadInfo.核心.map((core, index) => ({
                        核心编号: `核心${index + 1}`,
                        用户负载: core[`核心${index + 1}用户负载`],
                        系统负载: core[`核心${index + 1}系统负载`],
                        当前负载: core[`核心${index + 1}负载`]
                    })) : [];
                    let currentLoad = parseFloat(this.windowStore.loadInfo ? this.windowStore.loadInfo.当前负载 : 0);
                    let cpuLoadHistory = this.windowStore.cpuLoadHistory;
                    cpuLoadHistory.push(currentLoad);
                    if (cpuLoadHistory.length > this.maxPoints) {
                        cpuLoadHistory.shift();
                    }
                    this.windowStore.$patch({
                        cpuLoadHistory: cpuLoadHistory
                    });
                    if (!this.cpuTrendChart && this.$refs.cpuTrendChartRef) {
                        this.cpuTrendChart = echarts.init(this.$refs.cpuTrendChartRef);
                    }
                    this.cpuTrendChart.setOption({
                        tooltip: {
                            trigger: 'axis',
                            axisPointer: { type: 'cross' },
                            formatter: (params) => {
                                const date = new Date(params[0].axisValue);
                                const formattedDate = date.toLocaleTimeString();
                                return `时间: ${formattedDate}<br>负载: ${params[0].data} %`;
                            }
                        },
                        xAxis: {
                            type: 'category',
                            data: cpuLoadHistory.map((_, i) => {
                                const now = new Date();
                                now.setSeconds(now.getSeconds() - (cpuLoadHistory.length - i));
                                return now.toLocaleTimeString(); // 显示为 HH:mm:ss
                            }),
                            axisLabel: { rotate: 45 }, // 避免标签重叠
                            name: '时间'
                        },
                        yAxis: {
                            type: 'value',
                            max: 100,
                            name: '负载 (%)'
                        },
                        series: [{
                            name: 'CPU负载(%)',
                            type: 'line',
                            smooth: true,
                            data: cpuLoadHistory,
                            itemStyle: { color: '#f39c12' },
                            showSymbol: false
                        }],
                        animation: false
                    });
                } catch (error) {
                    console.log(error);
                }
            },
            async updateCpuTrendData() {
                try {
                    if (!this.cpuTrendChart && this.$refs.cpuTrendChartRef) {
                        this.cpuTrendChart = echarts.init(this.$refs.cpuTrendChartRef);
                    }

                    if (!this.cpuTrendChart) {
                        console.warn('CPU 趋势图未初始化');
                        return;
                    }
                    const result = await ipcRenderer.invoke('system-info', 'load');
                    if (result.code == 200) {
                        this.windowStore.updateSystem('load', result.data);
                        const currentLoad = parseFloat(result.data.当前负载);

                        let cpuLoadHistory = this.windowStore.cpuLoadHistory;
                        cpuLoadHistory.push(currentLoad);
                        if (cpuLoadHistory.length > this.maxPoints) {
                            cpuLoadHistory.shift();
                        }
                        this.windowStore.$patch({
                            cpuLoadHistory: cpuLoadHistory
                        });
                        const now = new Date();
                        this.cpuTrendChart.setOption({
                            xAxis: {
                                data: cpuLoadHistory.map((_, i) => {
                                    const time = new Date(now);
                                    time.setSeconds(time.getSeconds() - (cpuLoadHistory.length - i));
                                    return time.toLocaleTimeString();
                                })
                            },
                            series: [{ data: cpuLoadHistory }]
                        });
                    } else {
                        ElMessage({
                            message: result.msg,
                            type: 'error',
                            plain: true,
                        })
                    }
                } catch (error) {
                    console.log(error);
                }
            },
            startAutoUpdate() {
                setInterval(async () => {
                    try {
                        if (!this.cpuTrendChart) return;
                        await this.updateCpuTrendData();
                    } catch (error) {
                        console.log(error);
                    }
                }, 30000);
            },
            handleResize() {
                try {
                    if (this.memoryChart) {
                        this.memoryChart.resize();
                    }
                    if (this.diskChart) {
                        this.diskChart.resize();
                    }
                    if (this.cpuTrendChart) {
                        this.cpuTrendChart.resize();
                    }
                } catch (error) {
                    console.log(error);
                }
            },
            formatBytes(bytes) {
                try {
                    if (!bytes || bytes === 0) return '0 B';
                    const k = 1024;
                    const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
                    const i = Math.floor(Math.log(bytes) / Math.log(k));
                    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
                } catch (error) {
                    console.log(error);
                }
            },
            async buildProcessTree(processList) {
                try {
                    const map = {};
                    const roots = [];
                    // 创建映射
                    processList.forEach(proc => {
                        map[proc.pid] = { ...proc, children: [] };
                    });
                    // 构建树结构
                    processList.forEach(proc => {
                        const parentId = proc.parentPid;
                        if (parentId && map[parentId]) {
                            map[parentId].children.push(map[proc.pid]);
                        } else {
                            roots.push(map[proc.pid]);
                        }
                    });
                    this.pidMap = map;
                    //console.log(map);
                    return roots;
                } catch (error) {
                    console.log(error);
                }
            },
            getLevel(node, level = 0) {
                try {
                    if (!node.parentPid || node.parentPid === 0) return level;
                    const parent = this.pidMap[node.parentPid];
                    return parent ? this.getLevel(parent, level + 1) : level;
                } catch (error) {
                    console.log(error);
                }
            },
            getAllPids(data) {
                try {
                    let pids = [];
                    data.forEach(item => {
                        pids.push(item.pid);
                        if (item.children && item.children.length > 0) {
                            pids = pids.concat(this.getAllPids(item.children));
                        }
                    });
                    return pids;
                } catch (error) {
                    console.log(error);
                }
            },
            expandedALL() {
                try {
                    //console.log(this.expandedRowKeys);
                    if (this.expandedRowKeys.length == 0) {
                        this.expandedRowKeys = this.getAllPids(this.treeData);
                    } else {
                        this.expandedRowKeys = [];
                    }
                } catch (error) {
                    console.log(error);
                }
            }
        },
        beforeUnmount() {
            try {
                if (this.cpuTrendChart) {
                    this.cpuTrendChart.dispose();
                    this.cpuTrendChart = null;
                }
            } catch (error) {
                console.log(error);
            }
        }
    };
</script>
<style scoped>
    .el-row {
        margin-top: 10px;
    }

    .el-row>div {
        margin-bottom: 10px;
    }

    .el-col {
        border-radius: 4px;
    }

    .grid-content {
        border-radius: 4px;
        min-height: 36px;
    }

    .el-descriptions__title {
        font-size: 0.83em;
    }

    .card-header h5 {
        margin: 0;
    }

    .card-refresh-btn {
        float: right;
        margin-top: -25px;
        cursor: pointer;
    }

    .json-viewer-container {
        background-color: #f5f7fa;
        padding: 10px;
        border-radius: 4px;
        font-family: monospace;
        overflow-x: auto;
    }

    .el-table-v2 {
        border: 1px solid var(--el-table-border-color);
    }
</style>